import axios from "axios";
import { updateproducts } from "../../../../node-project/controllers/products.js";
//引入自己写的axios
import api from '../../http/apis/api.js'

export default {
  //状态，保存数据
  namespaced: true,
  state: {
    searchdata: {
      type: 'productName',
      value: '',
    },
    pageData: {
      currentPage: 1,
      pageSize: 5,
      totalNum: 3,
      totalPages: 1,
      data: [],
    },
    update: {
      imgname: '1600849452482-p19.jpg'
    },

  },
  //修改state里面的属性值唯一方法就是使用mutations
  mutations: {
    //获取的新页数
    setpageData(state, newpageData) {
      state.pageData = newpageData;
    },
    //获取修改的学生数据并赋值
    updateone(state, product1) {
      console.log(product1);
      state.update = product1;
    },
    addImgname(state, imgname) {
      state.update = {
        ...state.update,
        imgname
      }
    },
    //改变显示页数
    changeshowpage(state, newpage) {
      state.pageData.pageSize = newpage;
    },
    //首页
    firstpage(state) {
      state.pageData.currentPage = 1;
    },
    //尾页
    endpage(state) {
      state.pageData.currentPage = state.pageData.totalPages;
    },
    //上一页
    lastpage(state) {
      if (state.pageData.currentPage > 1)
        state.pageData.currentPage--;
    },
    //下一页
    nextpage(state) {
      if (state.pageData.currentPage < state.pageData.totalPages) {
        state.pageData.currentPage++;
      }
    },
  },
  //异步操作
  actions: {
    async showproducts(context, { type, value } = {}) {
      const { data } = await api.products.showproducts({
        currentPage: context.state.pageData.currentPage,
        pageSize: context.state.pageData.pageSize,
        type: context.state.searchdata.type,
        value: context.state.searchdata.value,
      });
      if (data.status) {
        context.commit('setpageData', data.data)
      }
    },
    //删除
    async delectone(context, _id) {
      const { data } = await api.products.delectone({ _id });
      context.dispatch('showproducts')
      // return data;                                   
    },
    //新增
    async addproduct(context, product) {
      console.log(product);
      const { data } = await api.products.addproduct(product)
      //如果返回的数据成功
      return data;
    },
    //获取修改的id
    async getproductid(context, _id) {
      const { data } = await api.products.getproductid(_id);
      if (data.status) {
        context.commit('updateone', data.data[0])
      }
    },
    //点击确认修改
    async updateproduct(context, newcategory) {
      const { data } = await api.products.updateproduct({ ...newcategory })
      return data;
    }
  }
}